package com.yys.gulimall.cart.interceptor;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yys.common.constant.AutherServerConstant;
import com.yys.common.constant.CartConstant;
import com.yys.common.to.user.MemberVo;
import com.yys.gulimall.cart.vo.UserInfoTo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 在目标执行之前判断用户登录状态,并封装传递给controller目标方法
 * @author zq
 * @version 1.0
 * @date 2021/3/31 16:44
 */
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        UserInfoTo userInfoTo = new UserInfoTo();
        HttpSession session = request.getSession();
        MemberVo memeber = (MemberVo) session.getAttribute(AutherServerConstant.LOGIN_USER);
        if(ObjectUtils.isNotNull(memeber)) {
            //登陆了
            userInfoTo.setUserId(memeber.getId());
        }
        Cookie[] cookies = request.getCookies();
        if(ObjectUtils.isNotEmpty(cookies)) {
            for (Cookie cookie : cookies) {
                String userKey = cookie.getName();
                if(CartConstant.TEMP_USER_COOKIE_NAME.equals(userKey)) {
                    userInfoTo.setUserkey(cookie.getValue());
                    userInfoTo.setTempUser(true);
                }
            }
        }
        // 分配一个临时用户
        if(StringUtils.isBlank(userInfoTo.getUserkey())) {
            String userKey = UUID.randomUUID().toString();
            userInfoTo.setUserkey(userKey);
        }
        threadLocal.remove();
        threadLocal.set(userInfoTo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        // 让浏览器保存 user-key
        UserInfoTo userInfoTo = threadLocal.get();
        if(!userInfoTo.isTempUser()){
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME,userInfoTo.getUserkey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
